<template>
  <div>
    <el-form ref="form" label-width="150px">
      <!--<el-form-item :label="item.label">
                    <el-tree
                      :data="monitorOptions"
                      :props="monitorTreeProps"
                      show-checkbox
                      node-key="id"
                      :disabled="addtype=='query'"
                      :default-expanded-keys="treeDefaultExpandedIds"
                      :default-checked-keys="monitorSelectArr">
                    </el-tree>
                  </el-form-item>-->

      <el-form-item :label="labelName">
        <el-cascader
          ref="monitorCascader"
          :options="monitorOptions"
          :key="monitorSelectKey"
          :props="props"
          :disabled="isDisabled"
          clearable
          filterable
          :show-all-levels="true"
          v-model="monitorSelectArr"
          @change="changeMonitorSelected"
        >
        </el-cascader>
      </el-form-item>
    </el-form>
    <el-table id="monitorListTable"
              :data="selectedMonitorList" row-key="id"
              style="width: 100%">
      <el-table-column
        prop="sort"
        label="排序" width="60">
        <template slot-scope="scope">
          <div class="monitor-sort-div">
            <div class="monitor-sort-icon">
              <div class="monitor-sort-icon-line"></div>
              <div class="monitor-sort-icon-line"></div>
              <div class="monitor-sort-icon-line"></div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="名称">
        <template slot-scope="scope">
          <el-input v-model="scope.row.name"
                    :disabled="isDisabled"
                    placeholder="请输入内容"
                    @change="changeTableListInput(scope.row,scope.$index)"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="monitor_num"
        label="测点">
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="120">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="deleteMonitorRow(scope.$index, selectedMonitorList)"
            type="text" size="small" :disabled="isDisabled">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="isWarning"
         style="font-size: 14px;color: #333333;padding: 16px 0 0 0;color: red;">
      （提示：拖拽行可对测点进行排序）
    </div>
  </div>
</template>

<script>
  import Sortable from "sortablejs"

  export default {
    name: "monitor-setting-list",
    props: {
      isWarning: {
        type: Boolean,
        default: () => {
          return true;
        },
      },
      isDisabled: {
        type: Boolean,
        default: () => {
          return false;
        },
      },
      isDragSort: {
        type: Boolean,
        default: () => {
          return false;
        },
      },
      labelName: {
        type: String,
        default: () => {
          return '';
        },
      },
      defaultSelectArr: {
        type: Array,
        default: () => {
          return [];
        },
      },
      defaultTableArr: {
        type: Array,
        default: () => {
          return [];
        },
      },
    },
    data() {
      return {
        monitorOptions: [],
        selectedMonitorList: [],
        isRefreshDragSort: false,
        refreshDraySortMonitors: [],

        monitorSelectKey: 0,
        props: {
          multiple: true,
          'expand-trigger': 'click',
          checkStrictly: false,
          value: "id",
          label: "name",
          children: 'children',
        },
        monitorSelectArr: [],
        // monitorTreeProps: {
        //   value: "id",
        //   label: "name",
        //   children: 'children',
        // },
      }
    },
    watch: {
      defaultSelectArr: {
        handler(val, oldVal) {
          if (val && val.length > 0) {
            this.monitorSelectArr = val;
          }
        }, immediate: true, deep: true,
      },
      defaultTableArr: {
        handler(val, oldVal) {
          if (val && val.length > 0) {
            this.selectedMonitorList = val;
          }
        }, immediate: true, deep: true,
      },
      isDragSort: {
        handler(val, oldVal) {
          if (typeof val == "boolean" && val) {
            this.initSortMonitorList();
          }
        }, immediate: true, deep: true,
      },
    },
    created() {
      this.getAllSelectList();
    },
    methods: {
      getAllSelectList() {
        let data = {};
        this.$apis.unity_monitor_set_all(data).then(res => {
          if (res.result == 0) {
            this.monitorOptions = res.data;
          }
        });
      },
      changeMonitorSelected(val) {
        let arr = [];
        for (let x = 0; x < val.length; x++) {
          let river_type = val[x][0];
          let river_id = val[x][1];
          let device_id = val[x][2];
          let monitor_id = val[x][3];
          let tmp = {};
          Object.assign(tmp, {
            river_type: river_type,
            river_id: river_id,
            device_id: device_id,
            monitor_id: monitor_id,
            name: '',
          });
          for (let i = 0; i < this.monitorOptions.length; i++) {
            let typeTmp = this.monitorOptions[i];
            if (typeTmp.id == river_type) {
              for (let j = 0; j < typeTmp.children.length; j++) {
                let riverTmp = typeTmp.children[j];
                if (riverTmp.id == river_id) {
                  for (let k = 0; k < riverTmp.children.length; k++) {
                    let deviceTmp = riverTmp.children[k];
                    if (deviceTmp.id == device_id) {
                      for (let l = 0; l < deviceTmp.children.length; l++) {
                        let monitorTmp = deviceTmp.children[l];
                        if (monitorTmp.id == monitor_id) {
                          Object.assign(tmp, {
                            id: monitorTmp.id,
                            monitor_num: monitorTmp.name,
                            name: riverTmp.name + '' + deviceTmp.name,
                            // name: typeTmp.name + '' + riverTmp.name + ''
                            //   + deviceTmp.name,
                          });
                        }
                      }
                    }
                  }
                }
              }
            }
          }
          arr.push(tmp);
        }
        this.selectedMonitorList = arr;
        this.$emit('updateTableList', this.selectedMonitorList);
      },
      deleteMonitorRow(index, rows) {
        const curDelRow = rows.splice(index, 1)[0];
        let t = [];
        t.push(curDelRow.river_type);
        t.push(curDelRow.river_id);
        t.push(curDelRow.device_id);
        t.push(curDelRow.monitor_id);

        let currentInd = -1;
        this.monitorSelectArr.find((value, index, arr) => {
          if (JSON.stringify(value) == JSON.stringify(t)) {
            currentInd = index;
          }
        });
        if (currentInd != -1) {
          let tt = this.monitorSelectArr.slice();
          tt.splice(currentInd, 1);
          this.monitorSelectArr = tt;
        }
        this.$emit('updateSelectedList', this.monitorSelectArr);
      },
      initSortMonitorList() {
        this.$nextTick(() => {
          const el = document.querySelectorAll(
            '.el-table__body-wrapper > table > tbody')[0]
          // const sortable = new Sortable(el, options);
          // 根据具体需求配置options配置项
          const sortable = new Sortable(el, {
            onStart: (evt) => {
              console.log('start drag')
            },
            onEnd: (evt) => { // 监听拖动结束事件
              // console.log(evt.oldIndex) // 当前行的被拖拽前的顺序
              // console.log(evt.newIndex) // 当前行的被拖拽后的顺序
              // 这里就可以写我们需要传给后台的逻辑代码
              // 我们有了 evt.oldIndex 和 evt.newIndex 这两个参数做索引，我们可以根据绑定在表格上面的 data 这个 Array 找到两个相应的记录。就可以针对数据进行操作啦。
              // 下面将拖拽后的顺序进行修改
              const currRow = this.selectedMonitorList.splice(evt.oldIndex,
                1)[0];
              this.selectedMonitorList.splice(evt.newIndex, 0, currRow);

              this.$emit('updateTableList', this.selectedMonitorList);
              // console.log(JSON.stringify(this.selectedMonitorList));
            }
          })
        });
      },
      changeTableListInput(item, index) {
        console.log(item, index)
        this.$emit('updateTableList', this.selectedMonitorList);
      },
    }
  }
</script>

<style scoped>
  .monitor-sort-div {
    /*text-align: center;
    text-align: -moz-center;
    text-align: -webkit-center;*/
    height: 40px;
    line-height: 40px;
  }

  .monitor-sort-icon {
    margin: 12px 6px;
    width: 16px;
    height: 16px;
    display: inline-block;
  }

  .monitor-sort-icon-line {
    width: 100%;
    height: 2px;
    margin: 2px auto;
    background-color: #999999;
  }
</style>
